package czk.concrent.juc.cyclicbarrier;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

/**
 * CyclicBarrier,其会自动恢复所使用的的计数值
 *
 * @Author:ChenZhangKun
 * @Date: 2020/7/25 16:30
 */
public class CyclicBarrierDemo {
    public static void main(String[] args) throws InterruptedException {
        // 初始化技术为2
        CyclicBarrier cyclicBarrier = new CyclicBarrier(2, () -> {
            System.out.println("各个线程运行结束啦");

        });
        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                try {
                    System.out.println("线程一开始啦");
                    cyclicBarrier.await();// 2-1=1
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
            Thread.sleep(2 * 1000);
            new Thread(() -> {
                try {
                    System.out.println("线程二开始啦");
                    cyclicBarrier.await(); // 1-1=0，此时两个线程才会运行
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
            // 3秒后考试运行cyclicBarrier的任务
            TimeUnit.SECONDS.sleep(3);
        }
    }
}
